<template>
  <view class="container">
    <button @click="scanCode">扫码1</button>
    <button @click="saoma">扫码2</button>
    <button @click="turn('/pages/video/video')">跳转</button>

    <button @click="createBarcode">扫码3</button>

    <div class="scanBox" style="display: none" ref="scanBox">
      <div ref="scanarea" id="scanarea" class="qrarea"></div>
      <div class="closeId scanBtn" @click="closeScan_4">关闭扫码</div>
      <div class="lineDiv" style="bottom: 80px"></div>
      <div class="selectqrcode scanBtn" @click="fromPhtoto">从相册选择二维码</div>
    </div>
    <button @click="startRecognize">扫码4</button>
  </view>
</template>

<script setup>
import { ref, reactive, onUnmounted } from 'vue';
import { sendLog } from '@/common/js/utils/index.js';

const info = reactive({
  scanInstance_3: null, // 扫码3
  scanInstance_4: null // 扫码4
});

const barcode = ref(null);
const scan = ref(null);
const scanBox = ref(null);
const scanarea = ref(null);
const href = 'https://uniapp.dcloud.io/component/README?id=uniui';

const turn = (url) => {
  uni.navigateTo({
    url: url
  });
};

const scanCode = () => {
  uni.scanCode({
    onlyFromCamera: true,
    success: function (res) {
      console.log('条码类型：' + res.scanType);
      console.log('条码内容：' + res.result);
    }
  });
};

const saoma = () => {
  console.log('平台', uni.getSystemInfoSync().platform);
  if (uni.getSystemInfoSync().platform === 'h5') {
    let barcodeInstance = null;
    barcodeInstance = plus.barcode.create('barcode', [plus.barcode.QR], {
      top: '100px',
      left: '0px',
      width: '100%',
      height: '500px',
      position: 'static'
    });
    barcodeInstance.onmarked = onmarked;
    plus.webview.currentWebview().append(barcodeInstance);
    function onmarked(type, result) {
      console.log('条码类型：' + type);
      console.log('条码内容：' + result);
    }
    barcodeInstance.start();
  } else {
    uni.scanCode({
      onlyFromCamera: true,
      success: function (res) {
        console.log('条码类型：' + res.scanType);
        console.log('条码内容：' + res.result);
      }
    });
  }
};

const closeScan_3 = () => {
  if (info.scanInstance_3) {
    info.scanInstance_3.close(); // 释放 barcode 对象
    info.scanInstance_3 = null; // 将 barcode 对象置为 null
  }
};
const createBarcode = () => {
  console.log('扫码--plus.barcode.create');
  try {
    if (info.scanInstance_3) {
      closeScan_3();
    }
    info.scanInstance_3 = plus.barcode.create(
      'barcode',
      [plus.barcode.QR],
      {
        top: '0px',
        left: '0px',
        width: '100%',
        height: '100%',
        position: 'static'
      },
      true
    );
    info.scanInstance_3.onmarked = function (type, result) {
      console.log('Success: type=' + type + ', result=' + result);

      closeScan_3();
      uni.showToast({
        title: '扫码成功: ' + result,
        icon: 'none'
      });
    };
    info.scanInstance_3.onerror = function (type, result) {
      closeScan_1();
      uni.showToast({
        title: '扫码失败，请重试！',
        icon: 'none'
      });
    };
    plus.webview.currentWebview().append(info.scanInstance_3);
    info.scanInstance_3.start();
  } catch (err) {
    console.log('扫码--plus.barcode.create', err);
  }
};

//关闭扫码
const closeScan_4 = () => {
  if (info.scanInstance_4) {
    info.scanInstance_4.close(); // 关闭扫码实例
    info.scanInstance_4 = null; // 将扫码实例置为 null
  }
  scanarea.value.innerHTML = ''; // 清空扫码区域的内容
  scanBox.value.style.display = 'none'; // 隐藏扫码界面
};

const onmarkcallback = (result) => {
  console.log('111111', result);
};

const startRecognize = () => {
  const onmarked = (type, result) => {
    uni.showToast({
      title: '扫码成功: ' + type + '-' + result,
      icon: 'none'
    });
    sendLog({
      type: type,
      result: result
    });

    onmarkcallback(result);
    closeScan_4();
  };

  const onerror = (error) => {
    console.log('error-扫描错误', error);
    closeScan_4();
  };

  try {
    scanBox.value.style.display = 'block'; // 显示扫码 div
    var filter = [plus.barcode.QR]; // 支持二维码和条形码
    var styles = {
      top: '0px',
      left: '0px',
      width: '100%',
      height: '100%',
      position: 'static'
    };
    info.scanInstance_4 = new plus.barcode.Barcode('scanarea', filter, styles, false);
    console.log('扫码控件初始化成功:', info.scanInstance_4);
    info.scanInstance_4.onmarked = onmarked;
    info.scanInstance_4.onerror = onerror;
    info.scanInstance_4.start(); // 开始扫码
    console.log('扫码已启动');
  } catch (err) {
    console.log('扫码初始化失败:', err);
  }
};

// 从相册中选择二维码图片

function onmarked2(type, result) {
  console.log('type', type);
  console.log('result', result);

  uni.showToast({
    title: '识别成功',
    icon: 'success'
  });
  sendLog({
    type: type,
    result: result
  });
}
const fromPhtoto = () => {
  closeScan_4();
  plus.gallery.pick(
    function (path) {
      sendLog({
        path: path
      });

      plus.barcode.scan(
        path,
        function (type, result) {
          // sendLog({
          //   type: type,
          //   result: result
          // });
          // alert('type1: ' + type + ' & result: ' + result);
          // console.log('识别成功:', result);
        },
        function (err) {
          uni.showToast({
            title: '识别失败',
            icon: 'none'
          });
          // sendLog({
          //   err: JSON.stringify(err)
          // });
          // console.error('扫码失败:', err.code, err.message);
        }
      );
    },
    function (err) {
      uni.showToast({
        title: '未成功读取图片',
        icon: 'none'
      });
      // sendLog({
      //   'err-err': err.message
      // });
      // console.error('选择图片失败:', err.message);
    }
  );
};

onUnmounted(() => {
  destroyBarcode();
  closeScan_4(); // 确保组件卸载时关闭扫码
});
</script>

<style>
.container {
  padding: 20px;
  font-size: 14px;
  line-height: 24px;
}

.scanBox {
  position: absolute;
  z-index: 99999999;
  top: 0px;
  left: 0;
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  padding-bottom: 150px;
  background: rgba(0, 0, 0, 1);
  display: none;
}
.qrarea {
  width: 100%;
  height: 100%;
  margin: auto;
}
.scanBtn {
  width: 100%;
  position: absolute;
  z-index: 5;
  bottom: 0;
  left: 0;
  color: #ffffff;
  text-align: center;
  height: 80px;
  line-height: 80px;
}
.lineDiv {
  width: 50%;
  position: absolute;
  z-index: 5;
  bottom: 0;
  left: 25%;
  height: 1px;
  background: linear-gradient(to right, rgba(255, 255, 255, 0) 0, rgba(255, 255, 255, 1) 50%, rgba(255, 255, 255, 0) 100%);
}
.closeId {
  bottom: 80px;
}
</style>
